package com.sinkdream.cms.service.serviceimpl;

import com.sinkdream.cms.VO.LoginVO;
import com.sinkdream.cms.dao.UserMapper;
import com.sinkdream.cms.exception.GlobalException;
import com.sinkdream.cms.model.User;
import com.sinkdream.cms.result.CodeMsg;
import com.sinkdream.cms.service.UserService;
import com.sinkdream.cms.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public String userRegister() {
        return null;
    }

    @Override
    public Boolean managerLogin(LoginVO loginVO) {
        if(loginVO == null){
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        // 判断手机号是否存在
        User dbUser = userMapper.getUserByPhone(Long.parseLong(mobile));
        if(dbUser == null){
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST) ;
        }
        //验证密码
        String dbPwd = dbUser.getUserPwd();
        if(!dbPwd.equals(password)){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR) ;
        }
        //验证登录权限
        boolean dbPermission = dbUser.getUserPermission();
            /**
            * 数据库中的0为false，非0为true；
            * 数据库为0 是用户，非0为管理员；
            * false是用户，true是管理员；
            * */
            if(dbPermission == false){
                throw new GlobalException(CodeMsg.PERMISSION_ERROR) ;
            }
            //生成cookie
            String token = UUIDUtil.uuid();
        return true;
    }

    @Override
    public CodeMsg userLogin(LoginVO loginVO) {
        if(loginVO == null){
            return CodeMsg.SERVER_ERROR;
        }
        String userMobile = loginVO.getMobile();
        String userPwd = loginVO.getPassword();
        // 判断手机号是否存在
        User dbUser = userMapper.getUserByPhone(Long.parseLong(userMobile));
        if(dbUser == null){
            return CodeMsg.MOBILE_NOT_EXIST;
        }
        //验证密码
        String dbPwd = dbUser.getUserPwd();
        if(!dbPwd.equals(userPwd)){
            return CodeMsg.PASSWORD_ERROR;
        }
        //验证用户账号是否被禁止登录
        Boolean dbAccountBan = dbUser.getUserAccountBan();
        if(dbAccountBan == true){
            /**
             * 数据库为0 false
             * 非0 为true，用户不能登录
             */
            return CodeMsg.ACCOUNT_ERROR;
        }
        //验证用户是否被禁言
        Boolean dbAccountStatus = dbUser.getUserAccountStatus();
        if(dbAccountStatus == true){
            /**
             * 数据库为0 false
             * 非0为true，用户不得发表评论以及不能发布“身边”新闻
             */
            return CodeMsg.ACCOUNT_STATUS_ABNORMAL;
        }
        return CodeMsg.SUCCESS;
    }
}
